package com.lastproject.ejb.util;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.AnswerDTO;
import com.lastproject.ejb.entities.Answer;
import com.lastproject.ejb.entities.QuestionOption;
import com.lastproject.ejb.entities.User;

/**
 * Session Bean implementation class AnswerConversion
 */
@Stateless
@LocalBean
public class AnswerConversion {

	@PersistenceContext
	EntityManager entityManager;

	/**
	 * Default constructor.
	 */
	public AnswerConversion() {
		// TODO Auto-generated constructor stub
	}

	public AnswerDTO fromEntity(Answer answer) {
		AnswerDTO answerDTO = new AnswerDTO();
		answerDTO.setId(answer.getId());
		answerDTO.setPersonalAnswer(answer.getPersonalAnswer());
		answerDTO.setIdUser(answer.getUser().getId());
		answerDTO.setIdquestionOption(answer.getQuestionOption().getId());
		return answerDTO;
	}

	public Answer fromDTO(AnswerDTO answerDTO) {
		Answer answer = entityManager.find(Answer.class, answerDTO.getId());

		if (answer == null) {
			answer = new Answer();
		}
		
		answer.setPersonalAnswer(answerDTO.getPersonalAnswer());
		answer.setQuestionOption(entityManager.find(QuestionOption.class, answerDTO.getIdquestionOption()));
		answer.setUser(entityManager.find(User.class, answerDTO.getIdUser()));
		return answer;
	}

}
